import CustomerTable from "@/components/CustomerTable";
import DictTag from "@/components/DictTag";
import ExportModal from "@/components/ExportModal";
// import PreviewModal from "@/components/HtmlPreviewModal";
import { CloudDownloadOutlined, CloudServerOutlined, ExportOutlined, PlusOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProColumns, ProTable } from "@ant-design/pro-components";
import type { FormInstance } from "antd";
import { Button, Divider, Dropdown, Input, Popconfirm, Space, Typography, message } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { default as NotifyForm, NotifyFormData } from "./components/NotifyForm";
import { getDict } from "@/services/api/module/system/dict";
import { getPageList, save } from "@/services/api/module/message/notifyList";
import FilterDrawer from "@/components/FilterDrawer";
import VditorPreview from "@/components/VditorPreview";
import { dict } from "@/utils/DictionaryCacheManager";

const Notify: React.FC = () => {
	const formTableRef = useRef<FormInstance>();
	const [filterTypeOptions, setFilterTypeOptions] = useState<any>([]);
	const [receiveModeOptions, setReceiveModeOptions] = useState<any>([]);
	const [formOpen, setFormOpen] = useState<boolean>(false);
	const actionRef = useRef<ActionType>();
	const [currentRowId, setCurrentRowId] = useState<number | undefined>();
	const [selectedRows, setSelectedRows] = useState<API.Message.NotifyVo[]>([]);
	const [exportOpen, setExportOpen] = useState<boolean>(false);
	const [previewOpen, setPreviewOpen] = useState<boolean>(false);
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [previewValue, setPreviewValue] = useState<string | undefined>(undefined);

	useEffect(() => {
		dict.getDict("	sys_notify_filter_type", true).then((data: any) => {
			setFilterTypeOptions(data);
		});
		dict.getDict("sys_receive_mode", true).then((data: any) => {
			setReceiveModeOptions(data);
		});
		dict.getDict("sys_notify_status", true).then((data: any) => {
			setStatusOptions(data);
		});
	}, []);

	const columns: ProColumns<API.Message.NotifyVo>[] = [
		{
			title: "公告标题",
			dataIndex: "title",
			valueType: "text"
		},
		{
			title: "接收方式",
			dataIndex: "receiveMode",
			valueType: "select",
			hideInSearch: true,
			valueEnum: receiveModeOptions,
			render: (_, record) => {
				return (
					<>
						{record?.receiveMode.length === 0 && <>-</>}
						{record?.receiveMode.map((item, index) => {
							return <DictTag key={index} type="tag" enums={receiveModeOptions} value={item.toString()} />;
						})}
					</>
				);
			}
		},
		{
			title: "筛选类型",
			dataIndex: "recipientFilterType",
			valueType: "select",
			valueEnum: filterTypeOptions,
			render: (_, record) => {
				return (
					<>
						<DictTag enums={filterTypeOptions} value={record?.recipientFilterType} />
					</>
				);
			}
		},
		{
			title: "截止日期",
			dataIndex: "deadline",
			valueType: "dateTime",
			hideInSearch: true
		},
		{
			title: "截止日期",
			dataIndex: "deadline",
			hideInTable: true,
			valueType: "dateTimeRange"
		},
		{
			title: "状态",
			dataIndex: "status",
			valueType: "select",
			valueEnum: statusOptions,
			render: (_, record) => {
				return <DictTag type="badge" enums={statusOptions} value={record?.status} />;
			}
		},
		{
			title: "操作",
			dataIndex: "option",
			width: "260px",
			fixed: "right",
			valueType: "option",
			render: (_, record: any) => {
				return (
					<>
						{!record.superAdmin && (
							<Space size={1} split={<Divider type="vertical" />}>
								<Typography.Link
									key="preview"
									onClick={() => {
										setPreviewOpen(true);
										setPreviewValue(record?.content);
										// setCurrentRowId(record.id);
									}}
								>
									预览
								</Typography.Link>
								{record?.status === "2" && (
									<Typography.Link
										type="success"
										key="push"
										onClick={() => {
											setCurrentRowId(record.id);
										}}
									>
										发布
									</Typography.Link>
								)}
								{record?.status === "1" && record?.status !== "0" && (
									<Typography.Link
										type="danger"
										key="close"
										onClick={() => {
											setCurrentRowId(record.id);
										}}
									>
										关闭
									</Typography.Link>
								)}
								<Typography.Link
									key="edit"
									onClick={() => {
										setCurrentRowId(record.id);
									}}
								>
									编辑
								</Typography.Link>
								<Popconfirm
									placement="bottomRight"
									title="提示"
									description={`确认要删除角色名称为: "${record.roleName}" 的角色吗？`}
									// onConfirm={async () => handleRemove(record.id)}
									okText="确认"
									cancelText="取消"
								>
									<Typography.Link type="danger" key="remove">
										删除
									</Typography.Link>
									{/* <Typography.Link
                    hidden={!access.hasPerms('system:role:remove')}
                    key="other"
                    onClick={async () => {}}
                  ></Typography.Link> */}
								</Popconfirm>
							</Space>
						)}
					</>
				);
			}
		}
	];
	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setFormOpen(false);
		setCurrentRowId(undefined);
		if (actionRef.current) {
			actionRef.current.reload();
		}
	};
	// 保存
	const handleSave = async (values: NotifyFormData) => {
		console.log(":");
		const requestParams = { ...values };
		requestParams.immortal = requestParams?.immortal ? 0 : 1;
		return new Promise((resolve, reject) => {
			save({ ...requestParams } as NotifyFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};

	const handleExport = async (values: any) => {
		// const downLoadParams = {
		//   ...values,
		//   ...formTableRef?.current?.getFieldsValue(),
		//   current: actionRef?.current?.pageInfo?.current,
		//   pageSize: actionRef?.current?.pageInfo?.pageSize,
		// };
		return new Promise<void>(reslove => {
			// downLoad.export('/system/post/export', downLoadParams);
			reslove();
		});
		// .then(() => {
		//   setExportOpen(false);
		//   return Promise.resolve();
		// })
		// .catch(() => {
		//   return Promise.reject();
		// });
	};
	const [searchFormValue, setSearchFormValue] = useState<any>(undefined);
	const [searchValue, setSearchValue] = useState<any>(undefined);
	// 请求列表数据
	const getTableList = async (params: any) => {
		return await getPageList({ ...searchFormValue, ...searchValue }).then(res => {
			return res;
		});
	};
	const handleOnSearch = async (value: any) => {
		setSearchValue({
			name: value
		});
		actionRef.current?.reload();
	};
	return (
		<>
			<ProTable<API.Message.NotifyVo>
				tableStyle={{ minHeight: "calc(100vh - 200px)" }}
				actionRef={actionRef}
				formRef={formTableRef}
				rowKey="id"
				key="notifyList"
				pagination={{
					showQuickJumper: true,
					showSizeChanger: true
				}}
				search={false}
				toolbar={{
					search: (
						<Space>
							<Input.Search placeholder="通过职位名称搜索" allowClear style={{ width: 280 }} onSearch={handleOnSearch} />
							<FilterDrawer
								columns={columns}
								tableActionRef={actionRef}
								onReset={() => {
									setSearchFormValue(undefined);
									actionRef?.current?.reload();
								}}
								onSubmit={(values: any) => {
									setSearchFormValue(values);
									actionRef?.current?.reload();
								}}
							/>
						</Space>
					)
				}}
				toolBarRender={() => {
					return [
						<Button type="primary" key="add" onClick={() => setFormOpen(true)}>
							<PlusOutlined /> 发布通知公告
						</Button>,
						// <Dropdown placement="bottom" trigger={["click"]} menu={{ items }} key="export">
						// 	<Button>
						// 		<CloudServerOutlined />
						// 		操作数据
						// 	</Button>
						// </Dropdown>,
						selectedRows.length > 0 && (
							<Button
								type="primary"
								danger
								key="delete"
								onClick={async () => {
									if (selectedRows.length <= 0) {
										message.warning("请选择一条或多条数据");
										return;
									}
									// 执行删除逻辑
								}}
							>
								批量删除
							</Button>
						)
					];
				}}
				columnsState={{
					persistenceKey: "pro-table-singe-demos",
					persistenceType: "localStorage",
					defaultValue: {
						option: { fixed: "right", disable: true }
					},
					onChange(value) {
						console.log("value: ", value);
					}
				}}
				request={getTableList}
				tableAlertRender={false}
				columns={columns}
				rowSelection={{
					onChange: (_, selectedRows) => {
						setSelectedRows(selectedRows);
					}
				}}
			/>
			{/* <NotifyForm
				onCancel={() => {
					setFormOpen(false);
					// setCurrentId(undefined);
				}}
				// @ts-ignore
				onSubmit={async (values: NotifyFormData) => {
					if (values.id) {
						// 修改
						// return await handleUpdate(values);
					} else {
						// 新增
						return await handleSave(values);
					}
				}}
				open={formOpen}
				id={currentRowId}
				receiveModeOptions={receiveModeOptions}
				filterTypeOptions={filterTypeOptions}
			/>
			<ExportModal
				onCancel={() => {
					setExportOpen(false);
				}}
				onSubmit={handleExport}
				title="导出公告信息"
				open={exportOpen}
				columns={columns}
			/> */}
			{/* <PreviewModal
				zIndex={1001}
				open={previewOpen}
				title="预览"
				width={"70%"}
				onCancel={() => {
					setPreviewOpen(false);
				}}
				value={previewValue}
			/> */}
		</>
	);
};

export default Notify;
